﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Web.UI;

public static class FileReferenceUtil
{
    public static string GetFilePath(Page thisPage, string relativeUrl, int fileType)
    {
        var path = thisPage.Server.MapPath(relativeUrl);
        if (File.Exists(path))
        {
            string strFormat = string.Empty;

            //Javascript
            if (fileType == 1)
            {
                strFormat = "<script type=\"text/javascript\" src=\"{0}?v={1}\"></script>";
            }
            //CSS
            else if (fileType == 2)
            {
                strFormat = "<link href=\"{0}?v={1}\" rel=\"stylesheet\" type=\"text/css\" />";
            }

            return string.Format(
                    strFormat,
                    thisPage.ResolveUrl(relativeUrl),
                    Hash(path)
                );
        }
        return string.Empty;
    }

    private static string Hash(string file)
    {
        using (var stream = File.OpenRead(file))
        using (var bs = new BufferedStream(stream))
        {
            using (var sha1 = new SHA1Managed())
            {
                byte[] hash = sha1.ComputeHash(bs);
                var result = new StringBuilder(2 * hash.Length);
                foreach (byte b in hash)
                {
                    result.AppendFormat("{0:X2}", b);
                }
                return result.ToString();
            }
        }
    }
}